package com.jbit.dm212.common;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

public class RedisUtils {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Resource
    private RedisTemplate<String,String> redisTemplate;
    public void set(String key,Object value){
        try {
            redisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(value));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置key-value,并设置过期时间
     * @param key
     * @param value
     * @param expire
     */
    public void set(String key,Object value,long expire){
        try {
            redisTemplate.opsForValue().set(key,objectMapper.writeValueAsString(value),expire, TimeUnit.SECONDS);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取
     * @param key
     * @return
     */
    public <T> T get(String key,Class<T> clazz){
        String json = redisTemplate.opsForValue().get(key);
        try {
            return objectMapper.readValue(json,clazz);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
    public String get(String key){
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除key
     * @param key
     * @return
     */
    public boolean delete(String key){
        return redisTemplate.delete(key);
    }

    public boolean hasKey(String key){
        return redisTemplate.hasKey(key);
    }

}
